Page({
  data: {
    balance: '0.00',
    positions: [],
    marketValue: '0.00',
    totalAsset: '0.00'
  },

  async onShow() {
    const openid = (await wx.cloud.callFunction({ name: 'getOpenId' })).result.openid;
    const db = wx.cloud.database();

    const userRes = await db.collection('user').where({ openid }).get();
    let balance = 0;
    if (userRes.data.length && userRes.data[0].balance !== undefined) balance = userRes.data[0].balance;

    const posRes = await db.collection('positions').where({ openid }).get();
    const positions = [];
    let marketValue = 0;

    await Promise.all(posRes.data.map(async (item) => {
      let cur = item.cost;
      await new Promise((resolve) => {
        wx.request({
          url: `https://hq.sinajs.cn/list=${item.code}`,
          method: "GET",
          success: (res) => {
            if (res.data) {
              const arr = res.data.split(',');
              if (arr.length > 3 && !isNaN(parseFloat(arr[3]))) {
                cur = parseFloat(arr[3]).toFixed(2);
              }
            }
            resolve();
          },
          fail: () => { resolve(); }
        });
      });
      const mv = (cur * item.quantity).toFixed(2);
      const profit = ((cur - item.cost) * item.quantity).toFixed(2);
      const profitRate = item.cost > 0 ? (((cur - item.cost) / item.cost) * 100).toFixed(2) : 0;
      marketValue += Number(mv);
      positions.push({
        ...item,
        currentPrice: cur,
        marketValue: mv,
        profit,
        profitRate
      });
    }));

    // 全部数据格式化为2位小数
    this.setData({
      balance: Number(balance).toFixed(2),
      positions,
      marketValue: Number(marketValue).toFixed(2),
      totalAsset: (Number(balance) + Number(marketValue)).toFixed(2)
    });
  },

  goToStockDetail(e) {
    const code = e.currentTarget.dataset.code;
    const name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `/pages/stock/stock?name=${encodeURIComponent(name)}&code=${code}`
    });
  },

  goIndex() {
    wx.switchTab({ url: '/pages/index/index' });
  },
  goSelfStock() {
    wx.switchTab({ url: '/pages/selfStock/selfStock' });
  },
  goAddressBook() {
    wx.switchTab({ url: '/pages/addressBook/addressBook' });
  }
});
